package com.kefu.smartCall.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.smartCall.mapper.ScTaskCallMapper;
import com.kefu.smartCall.mapper.ScTaskCallMsgMapper;
import com.kefu.smartCall.mapper.ScTaskMapper;
import com.kefu.smartCall.model.ScTask;
import com.kefu.smartCall.model.ScTaskCall;
import com.kefu.smartCall.model.ScTaskCallMsg;
import com.kefu.smartCall.vo.QueryTaskCallMsgVo;
import com.kefu.smartCall.vo.ScTaskCallBatchUpdateVo;
import com.kefu.smartCall.vo.ScTaskCallSearchVo;
import com.kefu.smartCall.vo.ScTaskStatVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ScTaskCallService extends AbstractKefuService<ScTaskCall> {
    @Resource
    protected ScTaskMapper scTaskMapper;
    @Resource
    protected ScTaskCallMapper scTaskCallMapper;
    @Resource
    protected ScTaskCallMsgMapper scTaskCallMsgMapper;

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    protected Class currentMapperClass() {
        //重写父类，返回当前mapper，调用saveBatch才不报错
        return ScTaskCallMapper.class;
    }


    public Page<ScTaskCall> queryTaskCallList(ScTaskCallSearchVo search) {
        Page<ScTaskCall> scTaskCallList = searchLambdaPage(search);
        Map<String, String> taskMap = scTaskMapper.selectList(Wrappers.lambdaQuery(ScTask.class).
                eq(ScTask::getTenantId, KefuContext.getTid())).stream().collect(Collectors.toMap(ScTask::getTaskId, ScTask::getTaskName));
        scTaskCallList.getRecords().forEach(scTaskCall -> {
            scTaskCall.setTaskName(taskMap.get(scTaskCall.getTaskId()));
            // 将所有的手机号进行脱敏处理: 13812345678 -> 138****5678
            scTaskCall.setCallTelephone(Stream.of(scTaskCall.getCallTelephone()).map(phone -> {
                if (StringUtils.isNotBlank(phone) && phone.length() > 7) {
                    return StrUtil.format("{}****{}", phone.substring(0, 3), phone.substring(phone.length() - 4));
                }
                return phone;
            }).collect(Collectors.joining(",")));
            scTaskCall.setCalleeNumber(Stream.of(scTaskCall.getCalleeNumber()).map(phone -> {
                if (StringUtils.isNotBlank(phone) && phone.length() > 7) {
                    return StrUtil.format("{}****{}", phone.substring(0, 3), phone.substring(phone.length() - 4));
                }
                return phone;
            }).collect(Collectors.joining(",")));
        });
        return scTaskCallList;
    }


    public List<ScTaskCallMsg> queryTaskCallMsg(QueryTaskCallMsgVo searchVo) {
        return scTaskCallMsgMapper.selectList(Wrappers.lambdaQuery(ScTaskCallMsg.class)
                .eq(ScTaskCallMsg::getTaskCallId, searchVo.getTaskCallId()).orderByAsc(ScTaskCallMsg::getMsgTime));
    }

    public List<String> batchUpdateCall(ScTaskCallBatchUpdateVo search) {
        List<String> message= Lists.newArrayList();
        if(search.getUpdateType()==1) {
            Optional.ofNullable(search.getSimpleUpdateVo())
                    .ifPresent(simpleUpdateVo->{
                        List<ScTaskCall> list = scTaskCallMapper.selectList(Wrappers.lambdaQuery(ScTaskCall.class)
                                .in(ScTaskCall::getTaskCallId, simpleUpdateVo.getTaskCallIds()));
                        message.addAll(recovery(list, simpleUpdateVo.getUpdateStatus()));
                    });

        }else if(search.getUpdateType()==2){
            Optional.ofNullable(search.getAdvancedUpdateVo())
                    .ifPresent(advancedUpdateVo->{
                        List<ScTaskCall> list = scTaskCallMapper.selectList(advancedUpdateVo.lambdaQuery());
                        message.addAll(recovery(list, advancedUpdateVo.getUpdateStatus()));
                    });
        }

        return message;
    }

    private List<String> recovery(List<ScTaskCall> list, Integer updateStatus) {
        List<String> message = Lists.newArrayList();
        LambdaUpdateWrapper<ScTaskCall> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.set(ScTaskCall::getSearchStatus, updateStatus);
        updateWrapper.set(ScTaskCall::getUpdateTime, KefuContext.getKefuContext().getNow());
        updateWrapper.in(ScTaskCall::getTaskCallId, list.stream().map(ScTaskCall::getTaskCallId).collect(Collectors.toList()));
        scTaskCallMapper.update(null, updateWrapper);
        message.add(String.format("总共修改了%d条记录",list.size()));
        return message;
    }

    public ScTaskStatVo queryTaskStat(String taskId) {
        return scTaskCallMapper.queryTaskStat(taskId);
    }
}
